package com.uek.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class StringUtil {

    private static final Pattern P_USRNAME = Pattern.compile("^[0-9a-zA-Z_\\-]{3,30}$", Pattern.CASE_INSENSITIVE);

    private static final Pattern P_EMAIL = Pattern.compile("^.+@.+\\..+$", Pattern.CASE_INSENSITIVE);

    private static final Pattern P_POSTAL = Pattern.compile("[0-9\\s\\-]+", Pattern.CASE_INSENSITIVE);


    /**
     * @param v1 latest version e.g. 1.2.0
     * @param v2 app version, e.g. 1.0.1
     * @return 1 if v1>v2
     */
    public static int checkAppVersion(String v1, String v2) {
        if (StringUtil.isEmpty(v1)) {
            return 0;
        }
        if (StringUtil.isEmpty(v2)) {
            return 1;
        }

        return v1.compareTo(v2);
    }

    public static String dateFortmat(long ts, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(new Date(ts));
    }

    public static String dateFortmat(long ts) {
        return dateFortmat(ts, "yyyy-MM-dd HH:mm:ss");
    }

    public static boolean isValidUsrName(String name) {
        if (StringUtil.isEmpty(name)) return false;

        return P_USRNAME.matcher(name).matches();
    }

    public static String fen2Yuan(long fen) {
        DecimalFormat df = new DecimalFormat("#0.00");
        return df.format(fen / 100d);
    }

    /**
     * @param yuan x.xx
     * @return
     */
    public static Long yuan2Fen(String yuan) {
        if (StringUtil.isEmpty(yuan)) return null;
        String[] list = yuan.split("\\.");
        if (list.length == 1) {
            return Long.parseLong(yuan) * 100;
        } else if (list.length == 2) {
            return Long.parseLong(list[0]) * 100 + Integer.parseInt(list[1]);
        }
        return null;
    }

    public static String yyyyMMddHHmmss(long st) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date(st));
    }

    public static boolean isValidPostal(String postal) {
        if (StringUtil.isEmpty(postal)) return false;

        return P_POSTAL.matcher(postal).matches();
    }

    public static boolean isValidEmail(String email) {
        if (StringUtil.isEmpty(email)) return false;

        return P_EMAIL.matcher(email).matches();
    }

    public static String emptyNull(String str) {
        return str == null ? "" : str;
    }

//    public static String urlDecode(String str) {
//        if (StringUtil.isEmpty(str)) return str;
//
//        if (str.indexOf('%') != -1) {
//            try {
//                return URLDecoder.decode(str,UTF_8);
//            } catch (Exception ignore) {
//            }
//        }
//        return str;
//    }

    /**
     * @param offsetStr e.g. +04:30 or -11:00
     * @return offset milliseconds or null (invalid value)
     */
    public static Integer parseTimeZoneOffset(String offsetStr) {
        if (StringUtil.isEmpty(offsetStr)) return null;

        char ch = offsetStr.charAt(0);
        int sign = ch == '-' ? -1 : 1;
        // rm sign + - ±
        if (ch == '+' || ch == '-' || ch == '±') {
            offsetStr = offsetStr.substring(1);
        }

        int loc = offsetStr.indexOf(":");
        if (loc == -1) return null;
        int hours = Integer.parseInt(offsetStr.substring(0, loc));
        int minutes = Integer.parseInt(offsetStr.substring(loc + 1));

        return sign * (hours * 3600 + minutes * 60) * 1000;
    }

    public static String clean(String str) {
        if (isEmpty(str)) return str;

        return str.replaceAll("\"", "").trim();
    }

    public static boolean isEmpty(String str) {
        return str == null || "".equals(str.trim());
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    /**
     * @param str
     * @return true if start with '*'
     */
    public static boolean isPasswordStr(String str) {
        if (isEmpty(str)) return false;

        return str.startsWith("*");
    }

    public static String localIp() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostAddress();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin) {
        return MD5Encode(origin, "utf-8");
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            else resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
        } catch (Exception ignored) {
        }
        return resultString;
    }

    private static final String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * 验证手机号
     *
     * @param mobile
     * @return
     */
    public static boolean validMobile(String mobile) {
        String regex = "(\\+\\d+)?1[345789]\\d{9}$";
        return Pattern.matches(regex, mobile);
    }



    /**
     * 获取指定位数随机整数
     *
     * @param len
     * @return
     */
    public static String getRandomString(int len) {
        return String.valueOf((long) ((Math.random() * 9 + 1) * Math.pow(10, len - 1)));
    }

    public static String substringAfter(String str, String separator) {
        if (isEmpty(str)) {
            return str;
        } else if (separator == null) {
            return "";
        } else {
            int pos = str.indexOf(separator);
            return pos == -1 ? "" : str.substring(pos + separator.length());
        }
    }

    public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = cs.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

    /**
     * 验证身份证
     *
     * @param idCard
     * @return
     */
    public static boolean validIdCard(String idCard) {
        String pattern = "^[1-9]\\d{5}[1-9]\\d{3}((0[1-9])|(1[0-2]))(0[1-9]|([1|2][0-9])|3[0-1])((\\d{4})|\\d{3}X)$";
        return Pattern.matches(pattern, "24072919941012209X");
    }

    /**
     * 验证车牌号
     *
     * @param content
     * @return
     */
    public static boolean validLicensePlate(String content) {
        String pattern = "([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}(([A-HJ-Z]{1}[A-HJ-NP-Z0-9]{5})|([A-HJ-Z]{1}(([DF]{1}[A-HJ-NP-Z0-9]{1}[0-9]{4})|([0-9]{5}[DF]{1})))|([A-HJ-Z]{1}[A-D0-9]{1}[0-9]{3}警)))|([0-9]{6}使)|((([沪粤川云桂鄂陕蒙藏黑辽渝]{1}A)|鲁B|闽D|蒙E|蒙H)[0-9]{4}领)|(WJ[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼·•]{1}[0-9]{4}[TDSHBXJ0-9]{1})|([VKHBSLJNGCE]{1}[A-DJ-PR-TVY]{1}[0-9]{5})";
        return Pattern.matches(pattern, content);
    }


}
